package com.bjy.qa.quartz;

import com.bjy.qa.enumtype.JobType;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * quartz 处理类
 */
@Component
public class QuartzHandler {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private Scheduler scheduler;

    /**
     * 创建定时任务
     * @param job job
     * @throws SchedulerException
     */
    public void createScheduleJob(com.bjy.qa.entity.project.Job job) throws SchedulerException {
        try {
            Class<? extends Job> jobClass = QuartzJob.class;
            JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(job.getId() + "").build();
            jobDetail.getJobDataMap().put("id", job.getId());
            jobDetail.getJobDataMap().put("type", job.getType().getValue());
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(job.getId() + "").withSchedule(scheduleBuilder).build();
            scheduler.scheduleJob(jobDetail, trigger);
            logger.info("Create Job Successful!");
        } catch (SchedulerException e) {
            logger.error("Create Job failed, cause: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 立即运行（运行一次定时任务）
     * @param job job
     * @throws SchedulerException
     */
    public void runScheduleJob(com.bjy.qa.entity.project.Job job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getId() + "");
        try {
            scheduler.triggerJob(jobKey);
            logger.info("Run Once Job Successful!");
        } catch (SchedulerException e) {
            logger.error("Run Once Job failed, cause: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 重启定时任务
     * @param job job
     * @throws SchedulerException
     */
    public void resumeScheduleJob(com.bjy.qa.entity.project.Job job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getId() + "");
        try {
            scheduler.resumeJob(jobKey);
            logger.info("Resume Job Successful!");
        } catch (SchedulerException e) {
            logger.error("Resume Job failed, cause: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 暂停定时任务
     * @param job job
     * @throws SchedulerException
     */
    public void pauseScheduleJob(com.bjy.qa.entity.project.Job job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getId() + "");
        try {
            scheduler.pauseJob(jobKey);
            logger.info("Pause Job Successful!");
        } catch (SchedulerException e) {
            logger.error("Pause Job failed, cause: " + e.getMessage());
            throw e;
        }
    }


    /**
     * 更新定时任务
     * @param job job
     * @throws SchedulerException
     */
    public void updateScheduleJob(com.bjy.qa.entity.project.Job job) throws SchedulerException {
        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(job.getId() + "");
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(job.getCronExpression())
                    .withMisfireHandlingInstructionDoNothing();
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            scheduler.rescheduleJob(triggerKey, trigger);
            logger.info("Update Job Successful!");
        } catch (SchedulerException e) {
            logger.error("Update Job failed, cause: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 删除定时任务
     * @param job job
     * @throws SchedulerException
     */
    public void deleteScheduleJob(com.bjy.qa.entity.project.Job job) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey(job.getId() + "");
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getId() + "");
        try {
            scheduler.pauseTrigger(triggerKey);
            scheduler.unscheduleJob(triggerKey);
            scheduler.deleteJob(jobKey);
            logger.info("Delete Job Successful!");
        } catch (SchedulerException e) {
            logger.error("Delete Job failed, cause: " + e.getMessage());
            throw e;
        }
    }

    /**
     * 获得 Trigger 实例
     * @param job job
     * @return
     */
    public CronTrigger getTrigger(com.bjy.qa.entity.project.Job job) {
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getId() + "");
        CronTrigger trigger = null;
        try {
            trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return trigger;
    }
}
